<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="类别/标签名称" v-model="whereQuery.name">
      </el-input>
      <el-select clearable style="width: 90px" class="filter-item" v-model="whereQuery.type" placeholder="类型" @change="handleFilter">
        <el-option v-for="item in tagTypeOptions" :key="item" :label="item | tagTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-select clearable style="width: 120px" class="filter-item" v-model="whereQuery.status" placeholder="是否可见" @change="handleFilter">
        <el-option v-for="item in statusTypeOptions" :key="item" :label="item | statusTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%" sortable="custom" @sort-change='handleOrder'>
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row._id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="创建时间" sortable prop="createdAt">
        <template slot-scope="scope">
          <span>{{scope.row.createdAt | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="190px" header-align="center" label="名称" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="类型">
        <template slot-scope="scope">
          <span>{{scope.row.type | tagTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="排序" sortable prop="index">
        <template slot-scope="scope">
          <span>{{scope.row.index}}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" width="210px" label="说明" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.content}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="90px" label="图标">
        <template slot-scope="scope" v-if="scope.row.icon && scope.row.icon.url">
          <el-popover ref="iconPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.icon.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:iconPopover type="text"  @click="openWindow(scope.row.icon.url)">icon</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" width="90px" label="选中">
        <template slot-scope="scope" v-if="scope.row.icon1 && scope.row.icon1.url">
          <el-popover ref="iconPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.icon1.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:iconPopover type="text"  @click="openWindow(scope.row.icon1.url)">icon1</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" width="90px" label="非选中">
        <template slot-scope="scope" v-if="scope.row.icon2 && scope.row.icon2.url">
          <el-popover ref="iconPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.icon2.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:iconPopover type="text"  @click="openWindow(scope.row.icon2.url)">icon2</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" width="90px" label="头图">
        <template slot-scope="scope" v-if="scope.row.cover && scope.row.cover.url">
          <el-popover ref="coverPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.cover.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:coverPopover type="text"  @click="openWindow(scope.row.cover.url)">cover</el-button>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="权重">
        <template slot-scope="scope">
          <span>{{scope.row.weight}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="是否可见">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 500px; margin-left:50px;'>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="说明">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="temp.content">
          </el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select class="filter-item" v-model="temp.type" placeholder="请选择">
            <el-option v-for="item in tagTypeOptions" :key="item" :label="item | tagTypeFilter" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="index" :rules="[{pattern: /^\d*$/,message: '排序只能输入整数值'}]">
          <el-input v-model.number="temp.index"></el-input>
        </el-form-item>
        <el-form-item label="权重" prop="weight" :rules="[{pattern: /^(\d+(\.\d{1,2})?)?$/,message: '权重只能输入数值'}]">
          <el-input v-model.number="temp.weight"></el-input>
        </el-form-item>
        <el-form-item label="是否可见">
          <el-select class="filter-item" v-model="temp.status" placeholder="请选择">
            <el-option v-for="item in statusTypeOptions" :key="item" :label="item | statusTypeFilter" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload class="avatar-uploader" action="https://upload-z1.qbox.me" accept="image/*" :data="iconObj" :multiple="false" :on-success='afterIconUpload' :before-upload="beforeIconUpload" :show-file-list="false">
            <img v-if="iconUrl" :src="temp.icon.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <el-button v-else size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="图标(选中)">
          <el-upload class="avatar-uploader" action="https://upload-z1.qbox.me" accept="image/*" :data="icon1Obj" :multiple="false" :on-success='afterIcon1Upload' :before-upload="beforeIcon1Upload" :show-file-list="false">
            <img v-if="icon1Url" :src="temp.icon1.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <el-button v-else size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="图标(非选中)">
          <el-upload class="avatar-uploader" action="https://upload-z1.qbox.me" accept="image/*" :data="icon2Obj" :multiple="false" :on-success='afterIcon2Upload' :before-upload="beforeIcon2Upload" :show-file-list="false">
            <img v-if="icon2Url" :src="temp.icon2.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <el-button v-else size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="头图">
          <el-upload action="https://upload-z1.qbox.me" accept="image/*" :data="coverObj" :multiple="false" :on-success='afterCoverUpload' :before-upload="beforeCoverUpload" :show-file-list="false">
            <img v-if="coverUrl" :src="temp.cover.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <el-button v-else size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetch, insert, deleteById, update } from '@/api/jb'
  import { getToken } from '@/api/qiniu'
  import waves from '@/directive/waves' // 水波纹指令
  import { MessageBox } from 'element-ui'

  const booleanOptions = [
    { key: true, value: '是' },
    { key: false, value: '否' }
  ]

  export default {
    name: 'tag',
    directives: {
      waves
    },
    data() {
      return {
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          skip: 0,
          limit: 10,
          where: {
            name: {
              $regex: '.*'
            },
            type: undefined,
            status: undefined
          },
          count: true,
          order: {
            updatedAt: -1
          }
        },
        whereQuery: {
          name: undefined,
          type: undefined,
          status: undefined
        },
        tagTypeOptions: [1, 2],
        statusTypeOptions: [1, 2],
        booleanOptions,
        temp: {
          _id: undefined,
          name: undefined,
          content: undefined,
          type: undefined,
          index: 0,
          cover: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon1: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon2: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          weight: undefined,
          status: 2
        },
        iconObj: { token: '', key: '' },
        icon1Obj: { token: '', key: '' },
        icon2Obj: { token: '', key: '' },
        coverObj: { token: '', key: '' },
        iconUrl: undefined,
        icon1Url: undefined,
        icon2Url: undefined,
        coverUrl: undefined,
        qiniuParams: {
          fileName: 'tag',
          platform: 'qiniu'
        },
        dialogFormVisible: false,
        jsonVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          name: [{ required: true, message: '名称不能为空', trigger: 'change' }],
          type: [{ required: true, message: '类型不能为空', trigger: 'change' }]
        }
      }
    },
    filters: {
      tagTypeFilter(type) {
        const tagType = ['分类', '标签']
        return type > 0 ? tagType[type - 1] : ''
      },
      statusTypeFilter(status) {
        const statusType = ['可见', '不可见']
        return status > 0 ? statusType[status - 1] : ''
      },
      json: (value) => { return JSON.stringify(value, null, 2) }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        fetch('Tag', this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      handleOrder(sort) {
        if (sort.prop) {
          const order = {}
          order[sort.prop] = sort.order === 'ascending' ? 1 : -1
          this.listQuery.order = order
        } else {
          this.listQuery.order = {
            updatedAt: -1
          }
        }
        this.getList()
      },
      handleFilter() {
        this.listQuery.skip = 0
        if (this.whereQuery.name) {
          this.listQuery.where.name = {
            $regex: '.*' + this.whereQuery.name + '.*'
          }
        } else {
          this.listQuery.where.name = undefined
        }
        if (this.whereQuery.type) {
          this.listQuery.where.type = this.whereQuery.type
        } else {
          this.listQuery.where.type = undefined
        }
        if (this.whereQuery.status) {
          this.listQuery.where.status = this.whereQuery.status
        } else {
          this.listQuery.where.status = undefined
        }
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.skip = (val - 1) * this.listQuery.limit
        this.getList()
      },
      resetTemp() {
        this.temp = {
          _id: undefined,
          name: undefined,
          content: undefined,
          type: undefined,
          index: 0,
          cover: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon1: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon2: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          weight: undefined,
          status: 2
        }
      },
      beforeUpload(file, type) {
        const _self = this
        return new Promise((resolve, reject) => {
          getToken(this.qiniuParams).then(response => {
            const key = response.data.data.name
            const token = response.data.data.token
            if (type === 1) {
              _self._data.iconObj.token = token
              _self._data.iconObj.key = key
            } else if (type === 2) {
              _self._data.coverObj.token = token
              _self._data.coverObj.key = key
            } else if (type === 3) {
              _self._data.icon1Obj.token = token
              _self._data.icon1Obj.key = key
            } else if (type === 4) {
              _self._data.icon2Obj.token = token
              _self._data.icon2Obj.key = key
            }
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },
      beforeIconUpload(file) {
        return this.beforeUpload(file, 1)
      },
      beforeIcon1Upload(file) {
        return this.beforeUpload(file, 3)
      },
      beforeIcon2Upload(file) {
        return this.beforeUpload(file, 4)
      },
      beforeCoverUpload(file) {
        return this.beforeUpload(file, 2)
      },
      afterCoverUpload(res) {
        this.temp.cover._id = res.data.file._id
        this.temp.cover.url = res.data.file.url
        this.coverUrl = res.data.file.url
      },
      afterIconUpload(res) {
        this.temp.icon._id = res.data.file._id
        this.temp.icon.url = res.data.file.url
        this.iconUrl = res.data.file.url
      },
      afterIcon1Upload(res) {
        this.temp.icon1._id = res.data.file._id
        this.temp.icon1.url = res.data.file.url
        this.icon1Url = res.data.file.url
      },
      afterIcon2Upload(res) {
        this.temp.icon2._id = res.data.file._id
        this.temp.icon2.url = res.data.file.url
        this.icon2Url = res.data.file.url
      },
      handleCreate() {
        this.resetTemp()
        this.coverUrl = undefined
        this.iconUrl = undefined
        this.icon1Url = undefined
        this.icon2Url = undefined
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.cover._id) {
              tempData.cover = undefined
            }
            if (!this.temp.icon._id) {
              tempData.icon = undefined
            }
            if (!this.temp.icon1._id) {
              tempData.icon1 = undefined
            }
            if (!this.temp.icon2._id) {
              tempData.icon2 = undefined
            }
            insert('Tag', tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (!this.temp.cover) {
          this.temp.cover = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
          this.coverUrl = undefined
        } else {
          this.coverUrl = this.temp.cover.url
        }
        if (!this.temp.icon) {
          this.temp.icon = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
          this.iconUrl = undefined
        } else {
          this.iconUrl = this.temp.icon.url
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.cover || !this.temp.cover._id) {
              tempData.cover = undefined
            }
            if (!this.temp.icon || !this.temp.icon._id) {
              tempData.icon = undefined
            }
            if (!this.temp.icon1 || !this.temp.icon1._id) {
              tempData.icon1 = undefined
            }
            if (!this.temp.icon2 || !this.temp.icon2._id) {
              tempData.icon2 = undefined
            }
            update('Tag', this.temp._id, tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById('Tag', row._id).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      },
      openWindow(value) {
        window.open(value)
      }
    }
  }
</script>
<style scoped>

</style>
